local conf = require("ufe.config")
local tair = require("ufe.util.tair")
local shared = require("ufe.util.shared")
local m = require("ufe.ufe_module")

--get apps needed to gray
function get_apps(premature)
    if premature then return end

    if not shared.is_ufe_apps_done() and shared.lock_ufe_apps() then
        local ok, err = m.get_apps_from_remote()
        if ok then
            ngx.log(ngx.INFO,"get ufe apps from remote success.")
        else
            err = err or "unknow error"
            m.load_conf_fail(nil, err)
        end
        shared.unlock_ufe_apps()
    end

    -- not done
    if not shared.is_ufe_apps_done() then
        local ok, msg = ngx.timer.at(3, get_apps)
        if not ok then
            ngx.log(ngx.EMERG,"cannot to get_apps, failed to create timer: ", msg)
        end
    end
end

ngx.log(ngx.DEBUG, "UFE init in init_worker_by_lua")

--only load apps at start time, set timer per worker
if not shared.is_ufe_apps_done() and shared.lock_ufe_apps() then
    local ok, msg = ngx.timer.at(0, get_apps)
    if not ok then
        ngx.log(ngx.EMERG,"cannot to get_apps, failed to create timer: ", msg)
    end
    shared.unlock_ufe_apps()
end
